package com.dhnsoft.代码随想录.栈与队列;

import java.util.*;

/**
 * ClassName: d07_347_前k个高频元素
 * Package: com.dhnsoft.代码随想录.栈与队列
 * Description:
 *
 * @Author dhn
 * @Create 2024/4/1 16:33
 * @Version 1.0
 */
public class d07_347_前k个高频元素 {

    public static int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int num : nums) {
            if(map.containsKey(num)){
                map.put(num,map.get(num)+1);
            }
            else{
                map.put(num,1);
            }
        }
        PriorityQueue<int[]> queue = new PriorityQueue<>(((o1, o2) -> o1[1]-o2[1]));
        for (Map.Entry<Integer, Integer> integerIntegerEntry : map.entrySet()) {
            int[] temp = new int[2];
            temp[0] = integerIntegerEntry.getKey();
            temp[1] = integerIntegerEntry.getValue();
            queue.offer(temp);
            if(queue.size()>k){
                queue.poll();
            }
        }
        int[] result = new int[k];
        int i=0;
        for (int[] ints : queue) {
            result[i++] = ints[0];
        }
        return result;

    }

    public static void main(String[] args) {
        topKFrequent(new int[]{1,1,1,2,2,3},2);
    }
}
